package com.example.foods.controller;

import cn.hutool.core.util.StrUtil;
import com.example.foods.common.Constants;
import com.example.foods.common.Utils;
import com.example.foods.domain.AdminInfo;
import com.example.foods.domain.AjaxResult;
import com.example.foods.domain.UpdateAdminInfo;
import com.example.foods.domain.UpdatePwdInfo;
import com.example.foods.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Slf4j
@RestController
public class AdminController {

    //日志记录器
    private static Logger logger= LoggerFactory.getLogger(AdminController.class);

    @Resource
    private AdminService adminService;

    @GetMapping("/code")
    public void generateCodeImage(HttpServletRequest req, HttpServletResponse resp) {
        //每个客户端在服务器端都关联一个HttpSession容器，使用该容器可以存储和客户端相关的数据
        HttpSession session = req.getSession();

        String code = Utils.generateRandomString(4);
        logger.debug("生成的验证码:"+code);
        //将验证码保存到session容器中
        session.setAttribute(Constants.SESSION_KEY_VERIFY_CODE, code);

        //动态创建图片
        BufferedImage img = new BufferedImage(Constants.VERIFY_IMAGE_WIDTH,
                Constants.VERIFY_IMAGE_HEIGHT,
                BufferedImage.TYPE_INT_RGB);
        //获取图形设备接口
        Graphics graphics = img.getGraphics();
        //背景.0
        graphics.setColor(Color.PINK);
        graphics.fillRect(0, 0, Constants.VERIFY_IMAGE_WIDTH, Constants.VERIFY_IMAGE_HEIGHT);
        //验证码
        graphics.setColor(Color.BLUE);
        graphics.setFont(new Font("Arial", Font.BOLD, 20));
        graphics.drawString(code, 10, Constants.VERIFY_IMAGE_HEIGHT / 2 + 6);

        //借助HttpServletResponse对象给客户端返回响应数据
        resp.setContentType("image/png");
        try {
            ImageIO.write(img, "png", resp.getOutputStream());
        } catch (IOException e) {
            logger.error("给客户端返回验证码图片时异常。"+e);
        }
    }

    @PostMapping("/admin/login")
    public AjaxResult login(@RequestBody  @Valid AdminInfo adminInfo, BindingResult bindingResult,HttpSession httpSession){
        //有校验错误
        if(bindingResult.hasFieldErrors()){
            return AjaxResult.error(-1,"请求无效!");
        }
        //验证码
        String code = (String)httpSession.getAttribute(Constants.SESSION_KEY_VERIFY_CODE);
        if(!adminInfo.getCode().equalsIgnoreCase(code)){
            return AjaxResult.error(-1,"验证码不正确!");
        }
        //账号和密码
        AdminInfo adminInfo1= this.adminService.findByAdminAccount(adminInfo.getAdminAccount());
        if(adminInfo1==null){
            return AjaxResult.error(-1,"账号不正确!");
        }
        if(Utils.checkPassword(adminInfo.getAdminPwd(),adminInfo1.getAdminPwd())){
            //登录成功后，会将用户对象存入session中，以便后续进行权限检查
            httpSession.setAttribute(Constants.SESSION_KEY_LOGINED_USER,adminInfo1);
            return AjaxResult.ok(adminInfo1);
        }
        return AjaxResult.error(-1,"密码不正确!");
    }


    @PostMapping("/admin/logout")
    public AjaxResult logout(HttpSession httpSession){
        logger.debug("清除session容器。。。");
        httpSession.invalidate();
        return AjaxResult.ok(true);
    }

   /* @PostMapping("/admin/updatePwd")
    public AjaxResult updatePwd(@RequestBody UpdatePwdInfo updatePwdInfo) {
        if(StrUtil.isBlank(updatePwdInfo.getPwd())){
            log.error("密码未输入");
            AjaxResult.ok(false);
        }
        adminService.updatePwd(updatePwdInfo);

        return AjaxResult.ok(true);
    }
    */

    @PostMapping("/admin/updateAdmin")
    public AjaxResult updateAdmin(@RequestBody UpdateAdminInfo updateAdminInfo) {
        if(StrUtil.isBlank(updateAdminInfo.getPwd())){
            log.error("密码未输入");
            AjaxResult.ok(false);
        }
        if(StrUtil.isBlank(updateAdminInfo.getMobile())){
            log.error("电话未输入");
            AjaxResult.ok(false);
        }
        adminService.updateRealName(updateAdminInfo);
        adminService.updatePwd(updateAdminInfo);
        adminService.updateMobile(updateAdminInfo);
        return AjaxResult.ok(true);
    }

}
